package com.bvr;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Vector;

import org.json.JSONException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class PropertyActivty extends Activity  {

	private PropertyDetail propertyDetail;
	int imagesCount;
	int currnetImageIndex;

	/* UI Controls Start */
	private TextView lblpropertyDetailTitle;
	private TextView lblpropertyDetailLocation;
	private TextView lblpropertyDetailAccomodation;
	private TextView lblpropertyDetailSleep;
	private TextView lblpropertyDetailBed;
	private TextView lblpropertyDetailBath;
	// private TextView lblpropertyDetailAvailable;
	private TextView lblpropertyDetailDesc;
	private TextView lblpropertyDetailRates;
	private TextView lblpropertyDetailCaption;
	private ImageView imgpropertyDetailImage;

	private Button btnShowDesc;
	private Button btnShowSummary;
	private Button btnShowCalender;

	RelativeLayout layoutDesc;
	RelativeLayout layoutSummary;

	private Button btnGoPrevious;
	private Button btnGoNext;
	/* UI Controls Ends */

	/* Web Service Variables Start */
	private static String URL = "";
	private static String METHOD_NAME = "";
	private static String NAMESPACE = "";
	private static String SOAP_ACTION = "";
	/* Web Service Variables Ends */

	private static String strPropertyId;
	private static int propertyId;
	private Runnable viewOrders;
	private ProgressDialog m_ProgressDialog = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.property_detail);
		setVariables();
		Bundle recdData = getIntent().getExtras();
		strPropertyId = recdData.getString("com.bvr.propertyId");
		propertyId = Integer.parseInt(strPropertyId.trim());

		viewOrders = new Runnable() {
			@Override
			public void run() {
				setProperty(propertyId);
			}
		};
		Thread thread = new Thread(null, viewOrders, "MagentoBackground");
		thread.start();
		m_ProgressDialog = ProgressDialog.show(PropertyActivty.this,
				"Please wait...", "Retrieving data ...", true);

	}

	private void setVariables() {
		URL = getString(R.string.url_property_detail);
		METHOD_NAME = getString(R.string.method_name_property_detail);
		NAMESPACE = getString(R.string.namespace_property_detail);
		SOAP_ACTION = getString(R.string.soap_action_property_detail);
	}

	public void setProperty(int propertyId) {
		try {
			parseWebService(propertyId);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		runOnUiThread(returnRes);
	}

	private Runnable returnRes = new Runnable() {
		@Override
		public void run() {
			m_ProgressDialog.dismiss();
			setUI();
		}
	};

	private void setUI() {
		lblpropertyDetailTitle = (TextView) findViewById(R.id.lblPropertyDetailTitle);
		lblpropertyDetailTitle.setText(propertyDetail.getTitle());

		lblpropertyDetailAccomodation = (TextView) findViewById(R.id.lblPropertyDetailAccomodation);
		lblpropertyDetailAccomodation.setText(propertyDetail.getAccomodation());

		// lblpropertyDetailAvailable = (TextView)
		// findViewById(R.id.propertyDetailAvailable);
		// lblpropertyDetailAvailable.setText(propertyDetail.getAvailable());

		lblpropertyDetailBath = (TextView) findViewById(R.id.lblPropertyDetailBathroomValue);
		lblpropertyDetailBath.setText(propertyDetail.getBath());

		lblpropertyDetailBed = (TextView) findViewById(R.id.lblPropertyDetailBedroomValue);
		lblpropertyDetailBed.setText(propertyDetail.getBed());

		lblpropertyDetailDesc = (TextView) findViewById(R.id.lblPropertyDetailDesc);
		lblpropertyDetailDesc.setText(propertyDetail.getDesc());

		lblpropertyDetailLocation = (TextView) findViewById(R.id.lblPropertyDetailLocation);
		lblpropertyDetailLocation.setText(propertyDetail.getLocation());

		lblpropertyDetailSleep = (TextView) findViewById(R.id.lblPropertyDetailSleepValue);
		lblpropertyDetailSleep.setText(propertyDetail.getSleep());

		lblpropertyDetailRates = (TextView) findViewById(R.id.lblPropertyDetailRatesValue);
		imgpropertyDetailImage = (ImageView) findViewById(R.id.imgPropertyDetail);

		// String theRates =
		// propertyDetail.getRate().toString().trim().replace("|", "\n");

		StringBuilder theRates = new StringBuilder();

		for (String str : splitString(propertyDetail.getRate().toString(), "|")) {
			theRates.append(str.trim() + "\n");
		}
		lblpropertyDetailRates.setText(theRates);

		lblpropertyDetailCaption = (TextView) findViewById(R.id.lblPropertyDetailImageCaption);
		lblpropertyDetailCaption.setText("");

		btnShowDesc = (Button) findViewById(R.id.btnPropertyDetailShowDesc);
		btnShowDesc.setOnClickListener(showDescListener);
		btnShowSummary = (Button) findViewById(R.id.btnPropertyDetailShowSummary);
		btnShowSummary.setOnClickListener(showSummaryListener);

		btnShowCalender = (Button) findViewById(R.id.btnPropertyDetailShowCalender);
		btnShowCalender.setOnClickListener(showCalenderListener);

		layoutDesc = (RelativeLayout) findViewById(R.id.rlayoutDesc);
		layoutSummary = (RelativeLayout) findViewById(R.id.rlayoutSummary);

		btnGoPrevious = (Button) findViewById(R.id.btnPropertyDetailGoPrevious);
		btnGoPrevious.setOnClickListener(goPreviousListener);

		btnGoNext = (Button) findViewById(R.id.btnPropertyDetailGoNext);
		btnGoNext.setOnClickListener(goNextListener);

		// By default show summary view
		showSummary();

		setImagesUrl();
		setFirstImage();

	}

	private OnClickListener showDescListener = new OnClickListener() {
		public void onClick(View view) {

			showDesc();
		}
	};

	private OnClickListener showSummaryListener = new OnClickListener() {
		public void onClick(View view) {
			showSummary();
		}
	};

	private OnClickListener showCalenderListener = new OnClickListener() {
		public void onClick(View view) {
			showCalender(view);
		}
	};

	private OnClickListener goPreviousListener = new OnClickListener() {
		public void onClick(View view) {
			goPreviousImage();
		}
	};

	private OnClickListener goNextListener = new OnClickListener() {
		public void onClick(View view) {
			goNextImage();
		}
	};

	private void goPreviousImage()
	{
		if (currnetImageIndex > 0) {
			currnetImageIndex--;
			String currentImageUrl = (String) propertyDetail.getImageUrls()
					.get(currnetImageIndex).toString();
			String[] strTemp = splitString(currentImageUrl, "|");
			String urlOnly = strTemp[0];
			String caption = strTemp[1];

			debugDisplay("URL is : " + urlOnly);
			debugDisplay("Caption is : " + caption);

			lblpropertyDetailCaption.setText(caption);
			imgpropertyDetailImage
					.setImageDrawable(GetImageFromUrl(urlOnly));
		}
	}
	

	private void goNextImage()
	{
		if (currnetImageIndex < imagesCount - 1) {
			currnetImageIndex++;
			String currentImageUrl = (String) propertyDetail.getImageUrls()
					.get(currnetImageIndex).toString();
			String[] strTemp = splitString(currentImageUrl, "|");
			String urlOnly = strTemp[0];
			String caption = strTemp[1];

			debugDisplay("URL is : " + urlOnly);
			debugDisplay("Caption is : " + caption);

			lblpropertyDetailCaption.setText(caption);
			imgpropertyDetailImage
					.setImageDrawable(GetImageFromUrl(urlOnly));
		}
		
	}
	
	private void setFirstImage() {
		String currentImageUrl = (String) propertyDetail.getImageUrls().get(0)
				.toString();
		String[] strTemp = splitString(currentImageUrl, "|");
		String urlOnly = strTemp[0];
		String caption = strTemp[1];

		debugDisplay("URL is : " + urlOnly);
		debugDisplay("Caption is : " + caption);

		lblpropertyDetailCaption.setText(caption);
		imgpropertyDetailImage.setImageDrawable(GetImageFromUrl(urlOnly));

	}

	private void showSummary() {
		layoutDesc.setVisibility(View.GONE);
		layoutSummary.setVisibility(View.VISIBLE);
	}

	private void showCalender(View view) {

		String avaialbeStr = propertyDetail.getAvailable().toString();

		if (avaialbeStr != null && avaialbeStr.length() > 0) {
			debugDisplay(propertyDetail.getAvailable().toString());
		} else {
			debugDisplay("No string found");
		}

		Intent propertyCalenderIntent = new Intent(view.getContext(),
				PropertyReservedCalenderActivity.class);
		propertyCalenderIntent.putExtra("com.bvr.propertyReservedDates",
				propertyDetail.getAvailable().toString());
		propertyCalenderIntent.putExtra("com.bvr.propertyTitle", propertyDetail
				.getTitle().toString());

		startActivityForResult(propertyCalenderIntent, 0);

	}

	private void showDesc() {
		layoutSummary.setVisibility(View.GONE);
		layoutDesc.setVisibility(View.VISIBLE);
	}

	private void setImagesUrl() {
		ArrayList<String> tempUrls = new ArrayList<String>();

		for (String strUrl : propertyDetail.getImage().split(",")) {
			tempUrls.add(strUrl);
		}
		propertyDetail.setImageUrls(tempUrls);

		// for(String tempStr : propertyDetail.getImageUrls())
		// {
		// debugDisplay(tempStr);
		// }

		imagesCount = propertyDetail.getImageUrls().size();
	}

	private String[] splitString(String original, String separator) {

		Vector nodes = new Vector();

		// Parse nodes into vector
		int index = original.indexOf(separator);

		while (index >= 0) {
			nodes.addElement(original.substring(0, index));

			original = original.substring(index + separator.length());

			index = original.indexOf(separator);

		}
		// Get the last node
		nodes.addElement(original);

		// Create split string array
		String[] result = new String[nodes.size()];

		if (nodes.size() > 0) {

			for (int loop = 0; loop < nodes.size(); loop++)

			{
				result[loop] = (String) nodes.elementAt(loop);

				// System.out.println(result[loop]);

			}

		}
		return result;
	}

	private Drawable GetImageFromUrl(String url) {
		try {
			InputStream is = (InputStream) new URL(url).getContent();
			Drawable d = Drawable.createFromStream(is, "src name");
			return d;
		} catch (Exception e) {
			debugDisplay("Error in getting image from url : " + e.getMessage());
			// System.out.println(e.getMessage());
			return null;
		}
	}

	/* Web Service Parsing */

	/**
	 * @throws IOException
	 * @throws XmlPullParserException
	 * @throws JSONException
	 */
	private void parseWebService(int propertyId) throws IOException,
			XmlPullParserException, JSONException {

		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		request.addProperty("propertyID", propertyId);

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = true;

		envelope.implicitTypes = true;
		envelope.encodingStyle = "utf-8";
		envelope.enc = SoapSerializationEnvelope.ENC2001;
		envelope.xsd = SoapEnvelope.XSD;
		envelope.xsi = SoapEnvelope.XSI;

		envelope.setOutputSoapObject(request);
		AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
				URL);
		envelope.addMapping(NAMESPACE, "PropertyDetail",
				new PropertyDetail().getClass());
		androidHttpTransport.call(SOAP_ACTION, envelope);
		androidHttpTransport
				.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

		androidHttpTransport.debug = true;
		SoapObject soapresultmsg = (SoapObject) envelope.getResponse();
		String strRecord = soapresultmsg.getProperty(0).toString();
		// debugDisplay(strRecord);

		try {
			PropertyDetail thepropertyDetail = new PropertyDetail();
			Ksoap2ResultParser
					.parseBusinessObject(strRecord, thepropertyDetail);
			propertyDetail = thepropertyDetail;

		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// return propertyDetail;
	}

	public void debugDisplay(String s) {
		System.out.println(s);
	}

	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		 int eventaction = event.getAction(); 
	        
	        int X = (int)event.getX(); 
	        int Y = (int)event.getY(); 

	        switch (eventaction ) { 

	        case MotionEvent.ACTION_DOWN: // touch down so check if the finger is on a ball 
	        	//goNextImage();
	              
	             break; 


	        case MotionEvent.ACTION_MOVE:   // touch drag with the ball 
	        	goNextImage();
	            
	             break; 

	        case MotionEvent.ACTION_UP: 
	        	//goNextImage();
	               // touch drop - just do things here after dropping 

	             break; 
	        } 
	        // redraw the canvas 
	        //invalidate(); 
	        

		return true;
	}

}
